package com.lsk.apipassenger.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lsk.internalcommon.DTO.ResponseResult;
import com.lsk.internalcommon.constant.TokenConstants;
import com.lsk.internalcommon.request.TokenRequest;
import com.lsk.internalcommon.util.JwtUtils;
import com.lsk.internalcommon.util.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result = true;
        String requestString = "";

        String token = request.getHeader("Authorization");
        TokenRequest tokenRequest = JwtUtils.checkToken(token);

        //判断token解析是否为null
        if (tokenRequest==null){
            requestString = "token invalid";
            result = false;
        }else {
            //拼接key
            String phone = tokenRequest.getPhone();
            String identity = tokenRequest.getIdentity();
            String tokenKey = RedisPrefixUtils.tokenKeyByPhone(phone, identity, TokenConstants.ACCESSTOKEN);
            //去redis中获取token
            String tokenRedis = redisTemplate.opsForValue().get(tokenKey);
            if ((tokenRedis==null) || (!tokenRedis.trim().equals(token.trim()))){
                requestString = "redis token is null";
                result = false;
            }
        }

        if (!result){
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ResponseResult.fail().setData(requestString).toString()));
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
